import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse} from 'axios'
import { api_url } from './config'

const server: AxiosInstance = axios.create({
    baseURL: api_url,
    timeout: 8 * 1000
})

// 错误处理
const err = (e: any): void => {
    console.log(e)
}

server.interceptors.request.use((config: AxiosRequestConfig): AxiosRequestConfig => {
    console.log('请求拦截')
    return config
}, err)

server.interceptors.response.use((res: any): Promise<any> => {
    console.log('请求响应')
    return new Promise((resolve?: any, reject?: any) => {
        if(res.status == 401) {
            reject()
        }
        else {
            resolve(res.data)
        }
    })
}, err)

export default {
    post: (url: string, data?: object): any => {
        return server({
            method: 'POST',
            data,
            url
        })
    },
    get: (url: string, data?: object): any => {
        return server({
            method: 'GET',
            data,
            url
        })
    }
}